{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "rEHcB3kqyHZ6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/10\n",
      "1875/1875 [==============================] - 3s 2ms/step - loss: 0.2014 - accuracy: 0.9404\n",
      "Epoch 2/10\n",
      "1875/1875 [==============================] - 4s 2ms/step - loss: 0.0810 - accuracy: 0.9749\n",
      "Epoch 3/10\n",
      "1875/1875 [==============================] - 3s 2ms/step - loss: 0.0535 - accuracy: 0.9835\n",
      "Epoch 4/10\n",
      "1875/1875 [==============================] - 3s 2ms/step - loss: 0.0382 - accuracy: 0.9879\n",
      "Epoch 5/10\n",
      "1864/1875 [============================>.] - ETA: 0s - loss: 0.0273 - accuracy: 0.9911\n",
      "Reached 99% accuracy so cancelling training!\n",
      "1875/1875 [==============================] - 3s 2ms/step - loss: 0.0273 - accuracy: 0.9911\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<tensorflow.python.keras.callbacks.History at 0x7fec94fc0e48>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "class myCallback(tf.keras.callbacks.Callback):\n",
    "  def on_epoch_end(self, epoch, logs={}):\n",
    "    if(logs.get('accuracy')>0.99):\n",
    "      print(\"\\nReached 99% accuracy so cancelling training!\")\n",
    "      self.model.stop_training = True\n",
    "\n",
    "mnist = tf.keras.datasets.mnist\n",
    "\n",
    "(x_train, y_train),(x_test, y_test) = mnist.load_data()\n",
    "x_train, x_test = x_train / 255.0, x_test / 255.0\n",
    "\n",
    "callbacks = myCallback()\n",
    "\n",
    "model = tf.keras.models.Sequential([\n",
    "  tf.keras.layers.Flatten(input_shape=(28, 28)),\n",
    "  tf.keras.layers.Dense(512, activation=tf.nn.relu),\n",
    "  tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n",
    "])\n",
    "model.compile(optimizer='adam',\n",
    "              loss='sparse_categorical_crossentropy',\n",
    "              metrics=['accuracy'])\n",
    "\n",
    "model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "Exercise2-Answer.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
